package com.ijava.base.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ijava.base.domain.Organization;
import com.ijava.base.domain.User;
import com.ijava.base.service.OrganizationService;
import com.ijava.util.DTreeBean;
import com.ijava.util.SystemConfig;

@Controller
@RequestMapping("/admin/organization.do")
@SessionAttributes("list")
public class OrganizationController {
	private static final Logger logger = LoggerFactory.getLogger(OrganizationController.class);
	@Autowired
	private OrganizationService service;
	
	@RequestMapping(params = "action=tree")
	public String tree(ModelMap modelMap, HttpSession session)
			throws Exception {
		try {
			String orgId = SystemConfig.getProperty("ORGANIZATION.ID");
			Organization organization = service.get(orgId);
			if(null == organization){
				User loginUser = (User)session.getAttribute("loginUser");
				String orgParentId = SystemConfig.getProperty("ORGANIZATION.PID");
				String orgCode = SystemConfig.getProperty("ORGANIZATION.CODE");
				String orgName = SystemConfig.getProperty("ORGANIZATION.NAME");
				organization = new Organization(orgParentId,orgCode,orgName,null);
				organization.setOrgId(orgId);
				organization.setOrgIsLeaf(0);
				organization.setOrgLevel(1);
				organization.setRowEnable(1);
				organization.setCrTime(new Date(System.currentTimeMillis()));
				organization.setCrUserId(loginUser.getUserId());
				service.persist(organization);
			}
			modelMap.addAttribute("orgId", organization.getOrgId());
			
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/organization/organizationIndex.jsp";
	}
	
	@RequestMapping(params = "action=subTree")
	public String subTree(ModelMap modelMap, Organization organization, HttpSession session,HttpServletRequest request)
			throws Exception {
		try {
			String context = request.getContextPath(); //session.getServletContext().getContextPath();
			List tree = new ArrayList();
			
			List dTreeList = new ArrayList();
			Organization topOrg = service.get(organization.getOrgId());
			dTreeList.add(new DTreeBean(topOrg.getOrgId(),topOrg.getOrgParentId(), topOrg.getOrgName(),
					context+"/admin/organization.do?action=list&orgLevel="+topOrg.getOrgLevel()+"&orgId="+topOrg.getOrgId(),
					topOrg.getOrgName(),"treeListFrame"));
			
			List list = service.findTree(organization.getOrgId(),tree);
			for (int i = 0; i < list.size(); i++) {
				
//				<c:url value="/admin/organization.do?action=list&orgId=${dTree.id}"/>
				Organization org = (Organization)list.get(i);
				DTreeBean dTree = new DTreeBean(org.getOrgId(),
						org.getOrgParentId(),
						org.getOrgName(),
						context+"/admin/organization.do?action=list&orgLevel="+org.getOrgLevel()+"&orgId="+org.getOrgId(),
						org.getOrgName(),"treeListFrame");
				dTreeList.add(dTree);
			}
			modelMap.addAttribute("list", dTreeList);
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/organization/organizationLeft.jsp";
	}

	@RequestMapping(params = "action=list")
	public String list(ModelMap modelMap, Organization organization, HttpSession session)
			throws Exception {
		try {
			List list = service.findWithPaging(organization);
			modelMap.addAttribute("list", list);
			modelMap.addAttribute("command",organization );
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/organization/organizationList.jsp";
	}
	
	@RequestMapping(params = "action=ajaxRemove")
	public void ajaxRemove(ModelMap modelMap, String orgId, HttpSession session,HttpServletResponse response)
			throws Exception {
		String res = "false";
		try {
			List list = service.findChild(new Organization(orgId));
			if(list.size() == 0){
				// has child node
				if(!"_".equals(orgId)){
					service.removeProcess(service.get(orgId));
				}
			}else{
				res = "true";
			}
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(res);
	}
	
	
	@RequestMapping(params = "action=saveEdit")
	public String saveEdit(ModelMap modelMap, Organization organization, HttpSession session)
			throws Exception {
		modelMap.addAttribute("code", "org.modify.success");
		try {
			User loginUser = (User) session.getAttribute("loginUser");
			service.saveAll(organization, loginUser);
		} catch (Exception e) {
			modelMap.addAttribute("code", "org.modify.failed");
			modelMap.addAttribute("isError", "true");
			logger.error("", e);
//			throw e;
		}
		return list(modelMap, organization, session);
	}
}

